package page;

import common.Object;
import common.User;
import common.Writings;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.interactions.Actions;

public class DoPostPage {
    private EdgeDriver edgeDriver = Object.getEdgeDriver();
    private final String Frontrurl = "http://82.156.186.83:8080/index.html";
    private LoginPage loginPage = new LoginPage();

    /**
     * 1.打开首页，登录用户
     * 2.查找“发布新贴”元素，点击
     * 3.找到特殊元素“发新帖”，进行判断
     */
    public void openDoPost(User user) throws InterruptedException {
        loginPage.login(user);

        Thread.sleep(5000);
        WebElement openDoPostButton = edgeDriver.findElement(By.cssSelector("#bit-forum-content > div.page-header.d-print-none > div > div > div.col-auto.ms-auto.d-print-none > div > div"));
        Thread.sleep(2000);
        openDoPostButton.click();
        Thread.sleep(2000);
        WebElement pageTitle = edgeDriver.findElement(By.cssSelector("#bit-forum-content > div.page-header.d-print-none > div > div > div > h2"));
        Thread.sleep(2000);
        String str = pageTitle.getText();
        System.out.println(str + "========================");
        if (str.equals("发新贴")) {


            System.out.println("打开发布帖子页面成功");
        } else {
            System.out.println("打开失败");
            System.out.println(str);
        }

    }

    public void publishPost(Writings writings, User user) throws InterruptedException {
        openDoPost(user);
        WebElement headerInput = edgeDriver.findElement(By.cssSelector("#article_post_title"));
        Thread.sleep(1000);
        headerInput.sendKeys(writings.getHeader());

        WebElement inputContent = edgeDriver.findElement(By.cssSelector("#edit-article > div.CodeMirror.cm-s-default.CodeMirror-wrap > div.CodeMirror-scroll > div.CodeMirror-sizer > div > div > div > div.CodeMirror-code > div > pre > span > span"));
        Actions action = new Actions(edgeDriver);
        action.doubleClick(inputContent)
                .sendKeys(Keys.DELETE)
                .perform();
        action.sendKeys(writings.getContent()).perform();

        if (writings.getHeader() == null || writings.getContent() == null) {
            System.out.println("内容或标题不能为空");
        } else {
            WebElement publishButton = edgeDriver.findElement(By.cssSelector("#article_post_submit"));
            Thread.sleep(1000);
            publishButton.click();

            System.out.println("帖子发布成功");
        }

    }

    public void close() {
        edgeDriver.close();
    }
}
